;(function(win, $){
	'use strict';
	//数据请求
	function queryData(){
        var params = {
    		queryTime : new Date(eleStation.time).format('yyyyMMddhhmmss'),
            element : eleStation.ele.ele_id,
            ptype : eleStation.ele.type == 'WIND' ? 'EDA' : eleStation.ele.type,
            area: '31'
        };
		$.get(CafeJS.CXT+'/monitor/getAwsStatData.do', params, function(result){
            tableData = null;
            pageNum = 1;
            $("#analysis-stationwin>div:last").hide();
			if(result.success){
				tableData = result.params.data;
				initTableData(tableData,true);
			}
		},"json");
	}
	//绑定事件
	function bindEvent(){
		//选择站点类型
		$(".as-station-type").off().on("click",function(){
			if(!$(this).hasClass("active")){
				$(this).addClass("active").siblings().removeClass("active");
				var type = $(this).data('sid');
				var newData = tableData;
				if (type != 2) {
					newData = $.grep(tableData, function(d){
	                    return type == d.type;
	                });
				}
				initTableData(newData, true);
			}
		});
		//升序
		$("#ast-asc").off().on("click",function(){
            tableData.sort(function (i, j) { return j.vals - i.vals });
            initTableData(tableData, true);
        });
        //降序
		$("#ast-desc").off().on("click",function(){
			tableData.sort(function (i, j) { return i.vals - j.vals });
			initTableData(tableData, true);
        });
        //下载
		$("#ast-download").off().on("click",function(){
            var uri = 'data:application/vnd.ms-excel;base64,';
            var template = '<html><head><meta charset="UTF-8"></head><body><table border="1">{table}</table></body></html>';
            var base64 = function(s){
                return window.btoa(unescape(encodeURIComponent(s)));
            };
            var format = function(s,c){
                return s.replace(/{(\w+)}/g,function(m,p){
                    return c[p];
                });
            };
            var $table = $('<table border="1">');
            var css = {
                "min-width" : "87px",
                "height" : "37px",
                "text-align" : "center"
			};
            var headcss = $.extend({},css,{
                "background-color" : "#d9dbe4",
                "font-weight" : "bold"
			});
            var thead = getThead();
            var $htr = $('<tr>');
            thead.forEach(function(t){
                $htr.append($("<td>").css(headcss).text(t.name));
			});
            $table.append($htr);
            if(tableData.length > 0){
                tableData.forEach(function(d,i){
                	var $tr = $('<tr>');
                    thead.forEach(function(t,j){
                    	if(0 == j){
                            $tr.append($("<td>").css(css).text(i+1));
						}else{
                            $tr.append($("<td>").css(css).text(d[t.id]));
						}
                    });
                    $table.append($tr);
				});
            }
            var ctx = {table : $table.html()};
            var a = document.createElement('a');
            a.href = uri + base64(format(template,ctx));
            var fileName = $("#as-title").text();
            a.download = fileName + '.xls';
            a.click();
        });
	}
	//初始化表格
	function initTable(){
		var thead = getThead();
		var $table = $("<table>");
		var $thead = $("<thead>");
        $table.append($thead);
        var $tr = $("<tr>");
        $thead.append($tr);
		for(var i = 0; i < 3; i++){
            thead.forEach(function(t){
            	var $td = $("<td>").attr("tid",t.id).text(t.name);
                if(t.cls){
                    $td.attr("title",t.name).addClass(t.cls);
				}
                $tr.append($td);
			})
		}
		$("#as-table").empty().append($table);
	}
	//初始化表格数据
	function initTableData(tableData,isRest){
        var $table = $("#as-table>table");
		if(tableData && tableData.length > 0){
			var $tbody = $("<tbody>");
            var $thtd = $table.find("thead td");
			for(var i = 0; i < 10; i++){
                var $tr = $('<tr>');
                var num = 0;
                $thtd.each(function(j){
                	var $td = $("<td>");
                        if (0 == j % 4) {
                            num = i + j / 4 * 10 + (pageNum - 1) * 30;
                            if(num < tableData.length) {
                                $td.text(num + 1);
                            }
                        } else if(tableData[num]){
                        	var tdTxt = tableData[num][$(this).attr("tid")];
                        	if(3 != j % 4){
                                $td.attr("title",tdTxt);
							}
                            $td.text(tdTxt);
                        }
                    $tr.append($td);
				});
                $tbody.append($tr);
			}
            $table.find("tbody").remove().end().append($tbody);
            if(isRest && tableData.length > 30){
                CafeJS.Pagination({
                    appendTo : "#analysis-stationwin>div:last",
                    pages : Math.ceil(tableData.length / 30),
                    call : function(num){
                        pageNum = num;
                        initTableData(tableData);
					}
				});
                $("#analysis-stationwin>div:last").show();
            }
		}else{
            $table.find("tbody").remove();
        }
	}
	//获取表头
	function getThead(){
        var thead = [
            {
                name : "序号"
            },
            {
                id : "name",
                name : "站点"
            },
            {
                id : "county",
                name : "所属区县"
            }];
        thead.push({
            id : 'vals',
            cls : "td-ele",
            name :eleStation.ele.ele_name
        });
        return thead;
	}
	//设置默认
	function setDef(){
		if(eleStation){
            var name = eleStation.ele.ele_name;
            $("#as-title").html("自动站<span>" + name + "</span>（" + eleStation.time + "）");
		}
	}
	//构造方法
	var Main = function(){
		this.init();
	};
	var eleStation = null;
	var sort = "asc";
	var tableData = [];
	var pageNum = 1;
	Main.prototype = {
		init : function(){
            CafeJS.models(['pagination'],function(){
                eleStation =  $("#modal_stationView").children().data("proInfo");
                setDef();
                initTable();
                bindEvent();
                queryData();
			});
		}
	};
	new Main();
})(window, jQuery);